package com.pureut.order.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pureut.common.core.web.controller.BaseController;
import com.pureut.common.core.web.domain.AjaxResult;
import com.pureut.common.core.web.page.TableDataInfo;
import com.pureut.common.log.annotation.Log;
import com.pureut.common.log.enums.BusinessType;
import com.pureut.common.security.annotation.RequiresPermissions;
import com.pureut.order.domain.SalesOrder;
import com.pureut.order.domain.SalesOrder2;
import com.pureut.order.domain.SalesOrderDetail;
import com.pureut.order.domain.SalesOrderDetail2;
import com.pureut.order.dto.SalesOrderDto;
import com.pureut.order.service.SalesOrder2Service;
import com.pureut.order.service.SalesOrderDetail2Service;
import com.pureut.order.service.SalesOrderDetailService;
import com.pureut.order.service.SalesOrderService;
import com.pureut.order.vo.*;

import com.pureut.system.api.vo.UpdateDataBySchedulingVo;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.sql.SQLException;
import java.util.List;
import java.util.stream.Collectors;

/***
 * 销售订单控制层
 * Author:C
 * Date:2022/12/01 9:13
 * @DESC
 */
@RestController
@RequestMapping("/sales-order")
public class SalesOrderController extends BaseController {

    @Resource
    SalesOrderService salesOrderService;

    @Resource
    private SalesOrder2Service salesOrder2Service;

    @Resource
    private SalesOrderDetail2Service salesOrderDetail2Service;

    @Resource
    private SalesOrderDetailService salesOrderDetailService;

    /**
     * 销售订单列表
     */
    @RequiresPermissions("order:saleOrder:list")
    @GetMapping("/list")
    public TableDataInfo list(SalesOrderVo salesOrderVo) {
        startPage();
        //查询销售订单列表
        List<SalesOrderDto> list = salesOrderService.getList(salesOrderVo);
        return getDataTable(list);
    }

    /**
     * 新增销售订单
     */
    @RequiresPermissions("order:sale:saleOrder:add")
    @Log(title = "新增销售订单", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult add(@Validated @RequestBody SalesOrderVo salesOrderVo) throws Exception {
        return toAjax(salesOrderService.addSalesOrder(salesOrderVo));
    }

    /**
     * 提交评审
     */
    @RequiresPermissions("order:sale:saleOrder:subExamine")
    @Log(title = "提交评审", businessType = BusinessType.UPDATE)
    @GetMapping("/submitReview/{id}")
    public AjaxResult submitReview(@PathVariable("id") Long id) {
        return toAjax(salesOrderService.submitReview(id));
    }


    /**
     * 审核撤销
     */
    @RequiresPermissions("order:sale:saleOrder:revoke")
    @Log(title = "审核撤销", businessType = BusinessType.UPDATE)
    @GetMapping("/deleteReview/{id}")
    public AjaxResult deleteReview(@PathVariable("id") Long id) {
        return toAjax(salesOrderService.deleteReview(id));
    }

    /**
     * 手动关结
     */
    @RequiresPermissions("order:sale:saleOrder:manualClosing")
    @Log(title = "手动关结", businessType = BusinessType.UPDATE)
    @PostMapping("/close")
    public AjaxResult close(@RequestBody SalesOrderVo salesOrderVo) {
        return toAjax(salesOrderService.close(salesOrderVo));
    }

    /**
     * 批量删除
     */
    @RequiresPermissions("order:sale:saleOrder:remove")
    @Log(title = "批量删除", businessType = BusinessType.DELETE)
    @DeleteMapping("/delete/{ids}")
    public AjaxResult delete(@PathVariable("ids") String ids) {
        return toAjax(salesOrderService.delete(ids));
    }

    /**
     * 修改
     */
    @RequiresPermissions("order:sale:saleOrder:edit")
    @Log(title = "修改", businessType = BusinessType.UPDATE)
    @PostMapping("/update")
    public AjaxResult update(@Validated @RequestBody SalesOrderVo salesOrderVo) throws SQLException {
        return toAjax(salesOrderService.updateSalesOrder(salesOrderVo));
    }

    /**
     * 查看
     */
    @RequiresPermissions("order:sale:saleOrder:query")
    @GetMapping("/view/{id}")
    public AjaxResult view(@PathVariable("id") Long id) {
        return AjaxResult.success(salesOrderService.getView(id));
    }

    /**
     * 合同上传
     */
    @RequiresPermissions("order:sale:saleOrder:contractUp")
    @Log(title = "合同上传", businessType = BusinessType.UPDATE)
    @PostMapping("/contractUpload")
    public AjaxResult contractUpload(@Validated @RequestBody ContractUploadVo contractUploadVo) throws Exception {
        return toAjax(salesOrderService.contractUpload(contractUploadVo));
    }

    /**
     * 销售订单审核
     */
    @RequiresPermissions("order:sale:saleOrder:examine")
    @Log(title = "销售订单审核", businessType = BusinessType.UPDATE)
    @PostMapping("/saleOrderReview")
    public AjaxResult saleOrderReview(@Validated @RequestBody OrderReviewVo orderReviewVo) {
        return toAjax(salesOrderService.saleOrderReview(orderReviewVo));
    }

    /**
     * 获取销售订单列表(其他模块调用)
     */
    @GetMapping("/getSaleOrderList")
    public TableDataInfo getSaleOrderList(SalesOrderVo salesOrderVo) {
        startPage();
        //查询销售订单列表
        List<SalesOrderDto> list = salesOrderService.getSaleOrderList(salesOrderVo);
        return getDataTable(list);
    }

    /**
     * 排程模块回传数据，修改销售订单状态及数据（feign调用）
     */
    @PutMapping("/updateDataByScheduling")
    public AjaxResult updateDataByScheduling(@RequestBody UpdateDataBySchedulingVo updateDataBySchedulingVo) {
        return AjaxResult.success(salesOrderService.updateDataByScheduling(updateDataBySchedulingVo));
    }

    /**
     * 根据销售订单号及物料编码获取明细信息
     */
    @GetMapping("/getDataBySaleNumberAndMaterialCode")
    public AjaxResult getDataBySaleNumberAndMaterialCode(String saleNumber, String materialCode) {
        return AjaxResult.success(salesOrderService.getDataBySaleNumberAndMaterialCode(saleNumber, materialCode));
    }

    /**
     * 根据销售订单修改对应明细状态（生产计划 feign调用）
     */
    @PostMapping("/updateSaleOrderDetailStatus")
    public void updateSaleOrderDetailStatus(@RequestBody UpdateSaleOrderDetailStatusVo updateSaleOrderDetailStatusVo) {
        salesOrderService.updateSaleOrderDetailStatus(updateSaleOrderDetailStatusVo);
    }

    /**
     * 成品称重页面回传数据至销售订单(成品称重 feign调用)
     */
    @PostMapping("/backData")
    public void backData(@RequestBody BackDataVo backDataVo) {
        salesOrderService.backData(backDataVo);
    }

    /**
     * Feign销售发货重量回传
     */
    @PostMapping("/updateShippingWeight")
    public boolean updateShippingWeight(@RequestBody BackDataVo backDataVo) {
        return salesOrderService.updateShippingWeight(backDataVo);
    }

    @PostMapping("/updateShippingWeightSub")
    public boolean updateShippingWeightSub(@RequestBody BackDataVo backDataVo) {
        return salesOrderService.updateShippingWeightSub(backDataVo);
    }

    /**
     * Fegin销售退货重量回传
     *
     * @param backDataVo
     * @return
     */
    @PostMapping("/updateShippingWeightBack")
    public boolean updateShippingOutWeight(@RequestBody BackDataVo backDataVo) {
        return salesOrderService.updateShippingOutWeight(backDataVo);
    }

    /**
     * feign销售发货退货重量回传（扣减）
     *
     * @param backDataVo
     * @return
     */
    @PostMapping("/updateShippingWeightSubBack")
    public boolean updateShippingWeightSubBack(@RequestBody BackDataVo backDataVo) {
        return salesOrderService.updateShippingWeightSubBack(backDataVo);
    }

    /**
     * 委外入库回传销售订单明细委外重量(委外入库fegin调用)
     */
    @PostMapping("/updateSubWeight")
    public boolean updateSubWeight(@RequestBody BackDataVo backDataVo) {
        return salesOrderService.updateSubWeight(backDataVo);
    }

    /**
     * 委外入库扣减销售订单明细委外重量(委外入库fegin调用)
     */
    @PostMapping("/updateSubWeightDelete")
    public boolean updateSubWeightDelete(@RequestBody BackDataVo backDataVo) {
        return salesOrderService.updateSubWeightDelete(backDataVo);
    }


    /**
     * 排程修改销售订单明细状态为已完成
     */
    @PostMapping("/updateSaleStatus")
    public boolean updateSaleStatus(@RequestBody BackDataVo backDataVo) {
        return salesOrderService.updateSaleStatus(backDataVo);
    }

    /**
     * 判断销售订单的明细状态，同步修改销售订单的状态
     */
    @PutMapping("/updateSaleDocument")
    public boolean updateSaleDocument(@RequestBody SaleDocumentVo saleDocumentVo) {
        return salesOrderService.updateSaleDocument(saleDocumentVo);
    }

    /**
     * 同步ERP
     *
     * @return
     */
    @Transactional
    @PostMapping("/getDataFromERP")
    public AjaxResult getDataFromERP() {
        List<SalesOrder2> salesOrder2List = salesOrder2Service.list();
        List<SalesOrder> salesOrderList = salesOrder2List.stream()
                .map(salesOrder2 -> {
                    SalesOrder salesOrder = new SalesOrder();
                    try {
                        BeanUtil.copyProperties(salesOrder2, salesOrder);
                        salesOrder.setId(null);

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    return salesOrder;
                })
                .collect(Collectors.toList());

        List<SalesOrderDetail2> salesOrderDetail2List = salesOrderDetail2Service.list();
        List<SalesOrderDetail> salesOrderDetailsList = salesOrderDetail2List.stream()
                .map(salesOrderDetail2 -> {
                    SalesOrderDetail salesOrderDetail = new SalesOrderDetail();
                    try {
                        BeanUtil.copyProperties(salesOrderDetail2, salesOrderDetail);
                        salesOrderDetail.setId(null);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    return salesOrderDetail;
                })
                .collect(Collectors.toList());


        return toAjax(salesOrderService.saveBatch(salesOrderList)
                && salesOrderDetailService.saveBatch(salesOrderDetailsList));
    }

}
